<template>
  <div>
    <div class="map-container" id="containerEdit" :style="styleObj"></div>
    <div class="control-panel">
      <button class="btn" @click="addRecord" :disabled="!currentPosition">新增记录</button>
      <button class="btn" @click="deleteSelected">删除选中</button>
    </div>
    <div class="records-list">
      <div v-for="(record, index) in records" :key="record.id" class="record-item" @click="selectRecord(record)" :class="{ selected: selectedRecord && selectedRecord.id === record.id }">
        <input v-model="record.note" placeholder="点击输入备注" @change="saveRecords" />
        <div class="coordinates">
          {{ record.lng.toFixed(6) }}, {{ record.lat.toFixed(6) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';

let amap = null; // 保持AMap实例

export default {
  data() {
    return {
      map: null,
      styleObj: {
        width: '100%',
        height: '70vh',
        minHeight: '500px'
      },
      records: [],
      selectedRecord: null,
      currentPosition: null,
      markers: new Map(),
      clickMarker: null
    };
  },
  async mounted() {
    await this.initMap();
    this.loadRecords();
    this.addMapClickListener();
  },
  methods: {
    async initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: 'd48e7f2bd17c16b4cb757cffbb694b90'
      };

      try {
        const AMap = await AMapLoader.load({
          key: '2b05e7179f91bbd5c2c8b9780493cf28',
          version: '2.0',
          plugins: [
            'AMap.ToolBar',
            'AMap.Scale', 
            'AMap.Geolocation',
            'AMap.Marker'
          ],
          resizeEnable: true
        });

        this.map = new AMap.Map('containerEdit', {
          zoom: 14,
          mapStyle: 'amap://styles/normal'
        });

        await this.setUserLocation(AMap);
        amap = AMap; // 保存AMap引用
      } catch (error) {
        console.error('地图初始化失败:', error);
        alert('地图加载失败，请检查网络连接');
      }
    },

    // 自动抓取用户的地理信息作为中心点，如果获取失败则使用默认福州市的坐标
    async setUserLocation(AMap) {
      return new Promise((resolve) => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 5000
        });

        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            this.currentPosition = {
              lng: result.position.lng,
              lat: result.position.lat
            };
            this.map.setCenter([this.currentPosition.lng, this.currentPosition.lat]);
            this.addUserLocationMarker(result.position);
            resolve();
          } else {
            console.warn('使用IP定位回退');
            this.map.setCity('福州市');
            // this.map.setZoom(15);  // 设置地图缩放级别  但是setCity之后 缩放无效
            resolve();
          }
        });
      });
    },

    addUserLocationMarker(position) {
      if (amap) {
        new amap.Marker({
          position: [position.lng, position.lat],
          content: '<div class="user-location-marker"></div>',
          map: this.map
        });
      }
    },

    // 添加点击地图事件
    addMapClickListener() {
      this.map.on('click', (e) => {
        this.clearTempMarker();
        this.createTempMarker(e.lnglat);
        this.currentPosition = {
          lng: e.lnglat.getLng(),
          lat: e.lnglat.getLat()
        };
      });
    },

    // 清除临时标记
    clearTempMarker() {
      if (this.clickMarker) {
        this.clickMarker.setMap(null);
        this.clickMarker = null;
      }
    },

    // 创建临时标记
    createTempMarker(lnglat) {
      if (amap) {
        this.clickMarker = new amap.Marker({
          position: lnglat,
          content: '<div class="temp-marker"></div>',
          map: this.map
        });
      }
    },

    addRecord() {
      if (!this.currentPosition) return;

      const newRecord = {
        id: Date.now(),
        ...this.currentPosition,
        note: '',
        marker: null
      };

      this.records.push(newRecord);
      this.addMapMarker(newRecord);
      this.saveRecords();
      this.clearTempMarker();
    },

    // 添加地图标记
    addMapMarker(record) {
      if (amap) {
        const marker = new amap.Marker({
          position: [record.lng, record.lat],
          content: `<div class="record-marker">${record.note || ''}</div>`,
          map: this.map
        });

        marker.on('click', () => this.selectRecord(record));
        this.markers.set(record.id, marker);
      }
    },

    saveRecords() {
      localStorage.setItem('geoRecords', JSON.stringify(
        this.records.map(r => ({
          id: r.id,
          lng: r.lng,
          lat: r.lat,
          note: r.note
        }))
      ));

      // 更新地图上对应标记的note
      this.records.forEach(record => {
        const marker = this.markers.get(record.id);
        if (marker) {
          marker.setContent(`<div class="record-marker">${record.note || ''}</div>`);
        }
      });
    },

    selectRecord(record) {
      if (!record) {
        console.warn('传入的record为null或undefined');
        return;
      }
      this.selectedRecord = record;
      this.map.setCenter([record.lng, record.lat]);
      this.map.setZoom(16);
    },

    deleteSelected() {
      if (!this.selectedRecord) return;

      this.records = this.records.filter(r => r.id !== this.selectedRecord.id);
      this.removeMapMarker(this.selectedRecord.id);
      this.saveRecords();
      this.selectedRecord = null;
    },

    removeMapMarker(id) {
      const marker = this.markers.get(id);
      if (marker) {
        marker.setMap(null);
        this.markers.delete(id);
      }
    },

    // 加载记录
    loadRecords() {
      const data = localStorage.getItem('geoRecords');
      if (data) {
        try {
          const parsedData = JSON.parse(data);
          console.log('解析后的数据:', parsedData); // 日志
          this.records = parsedData;
          console.log('更新后的records:', this.records); // 日志
          parsedData.forEach(r => this.addMapMarker(r));
        } catch (error) {
          console.error('解析记录失败:', error);
        }
      } else {
        console.log('localStorage中没有找到记录'); // 日志
      }
    },
  },

};
</script>

<style>
.map-container {
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.control-panel {
  margin: 16px 0;
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.records-list {
  margin-top: 20px;
}

.record-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  margin-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
}

.record-item.selected {
  border-color: #409eff;
  background-color: #f5f7ff;
}

.record-item input {
  border: 1px solid #dcdfe6;
  padding: 4px;
  width: 200px;
  margin-right: 12px;
}

.user-location-marker {
  width: 20px;
  height: 20px;
  background: #409eff;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.temp-marker {
  width: 16px;
  height: 16px;
  background: #67c23a;
  border-radius: 50%;
  border: 2px solid white;
}

.record-marker {
  display: block;
  width: 200px;
  height: 36px;
  padding: 4px 8px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  border: 1px solid #409eff;
}
</style>